<template>
  <div class="app-container fix-padding-bottom">
    <div class="stat-case">
      <el-row>
        <el-col :span="4">
          <div class="sidebar-t">
            统计报表
          </div>
          <Sidebar class="sidebar-container" />
        </el-col>
        <el-col
          :span="20"
          class="r-cont"
        >
          <div class="m-title">
            <i
              class="el-icon-arrow-left back-report-view"
              @click="backReportView"
            />
            案件覆盖率统计表
          </div>
          <div class="r-top">
            <span class="l">
              图形详情
            </span>
            <span class="r">
              <em>组织：{{ org||'---' }}</em>
              <em>报表日期：{{ genDate ||'---' }}</em>
              <em>周期：{{ period ||'---' }}</em>
            </span>
          </div>
          <el-row
            :class="{'chart': true, 'nodata': isNoData}"
            :gutter="0"
          >
            <el-col :span="12">
              <div :class="{'area': true, 'sum': isSum0}">
                <i />
                <PieChart
                  :sum-case="sumCaseData"
                  class="sum-case"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div :class="{'area': true, 'major': isMajor0}">
                <i />
                <PieChart
                  :major-case="majorCaseData"
                  class="major-case"
                />
              </div>
            </el-col>
          </el-row>
          <!-- <div class="title">未触达占比</div> -->
          <el-row class="unreach-percent">
            <el-col :span="12">
              <div class="per">
                已分配3天案件未触达占比 {{ typeof UnCoverRate3==='number'&&UnCoverRate3+'%'||'---' }}
              </div>
            </el-col>
            <el-col :span="12">
              <div class="per">
                已分配7天案件未触达占比 {{ typeof UnCoverRate7==='number'&&UnCoverRate7+'%'||'---' }}
              </div>
            </el-col>
          </el-row>
          <div class="title">
            表格详情
            <el-button
              v-waves
              class="filter-item download"
              type="primary"
              :loading="downloadLoading"
              @click="downloadExcel"
            >
              下载报表
            </el-button>
          </div>
          <el-table
            ref="singleTable"
            v-loading.body="listLoading"
            class="table-detail"
            stripe
            center
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            :newpoly="isWin32"
            height="330"
            :data="tableData"
            @current-change="handleCurrentChange"
          >
            <el-table-column
              width="130"
              :label="roleModel"
            >
              <template slot-scope="scope">
                {{ scope.row.unitName || '---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="190"
              label="组织"
            >
              <template slot-scope="scope">
                <!--
			              {{scope.row.deptName||'---'}}/{{scope.row.teamName||'---' }}
				        	 -->
                {{ scope.row.aggrName||'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="120"
              prop="assignCount"
              label="分配案件数量"
            />
            <el-table-column
              width="120"
              label="案件触达率占比"
            >
              <template slot-scope="scope">
                {{ scope.row.coverRate?scope.row.coverRate+'%':'---' }}
              </template>
            </el-table-column>
            <el-table-column
              width="120"
              label="未触达案件数"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count0 }}
              </template>
            </el-table-column>
            <el-table-column
              width="130"
              label="案件触达1次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count1 }}
              </template>
            </el-table-column>
            <el-table-column
              width="130"
              label="案件触达2次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count2 }}
              </template>
            </el-table-column>
            <el-table-column
              width="130"
              label="案件触达3次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count3 }}
              </template>
            </el-table-column>
            <el-table-column
              width="130"
              label="案件触达4次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count4 }}
              </template>
            </el-table-column>
            <el-table-column
              width="130"
              label="案件触达5次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count5 }}
              </template>
            </el-table-column>
            <el-table-column
              width="135"
              label="案件触达5+次数量"
            >
              <template slot-scope="scope">
                {{ scope.row.commonCase.count5plus }}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script type="text/javascript">

import { Sidebar } from '@/views/layout/components'
import { parseTime } from '@/utils'
import waves from '@/directive/waves'
import { route_origins } from '@/api/routes'
import { reportViewStatCase, reportCoverExport } from '@/api/statReport'
import PieChart from './components/PieChart'
import { getExcelHeaderArray } from '@/vendor/ReadExcel'
import * as base64Str from '@/utils/base64Str'

const Export2Excel = import('@/vendor/Export2Excel')

export default {
  name: 'StatCase',
  directives: {
    waves
  },
  components: {
    Sidebar,
    PieChart
  },
  filters: {
    filterYMD(date) {
      return date ? parseTime(date, '{y}-{m}-{d}') : ''
    },
    filterYMDHMS(date) {
      return date ? parseTime(date) : ''
    }
  },
  data() {
    return {
      org: '',
      genDate: '',
      period: '日',
      isNoData: false,
      isSum0: false,
      isMajor0: false,
      sumCaseTitle: '案件总计',
      sumCaseData: {
        backgroundColor: '#ffffff',
        title: {
          text: this.sumCaseTitle,
          left: 111,
          top: 138,
          textStyle: {
            fontSize: 14,
            fontWeight: 'bolder',
            color: '#5B5D5F'
          }
          // subtext: 'test',
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          // type: 'scroll',
          // pageIconColor: 'black',
          // pageIconSize: 11,
          right: 20,
          top: 60,
          bottom: 10,
          // left: 'right',
          // selectedMode: 'single',
          data: [],
          textStyle: {
            color: '#5B5D5F',
            fontSize: 11
          }
          /* selected: {
					    '未触达案件数': true,
					    '案件触达1次数量': false
					} */
        },
        calculable: true,
        series: [{
          name: '案件总计',
          type: 'pie',
          clockwise: false,
          // selectedOffset: 30,
          // minAngle: 10,
          itemStyle: {
            // shadowColor: 'rgba(212,217,218,0.44)',
            shadowColor: 'rgba(0,0,0,0.24)',
            shadowBlur: 15
            // borderWidth: 10,
            // borderType: 'solid',
            // borderColor: 'inherit'
          },
          roseType: 'radius',
          radius: [55, 105],
          center: ['30%', '50%'],
          label: {
            /* normal: {
							show: true
						}, */
            formatter: '{d}%',
            fontSize: 11,
            position: 'inside'
          },
          data: [],
          animationEasing: 'cubicInOut',
          animationDuration: 2600
        }],
        color: ['#87C9FF', '#879DFF', '#9A87FF', '#CD99FF', '#D477C0', '#B15E97', '#B15E77', '#994949', '#546570', '#DAC53E', '#B9DA3E']
      },
      majorCaseTitle: '重点案件',
      majorCaseData: {
        backgroundColor: '#ffffff',
        title: {
          text: this.majorCaseTitle,
          left: 111,
          top: 138,
          textStyle: {
            fontSize: 14,
            fontWeight: 'bolder',
            color: '#5B5D5F'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 20,
          top: 60,
          bottom: 10,
          data: [],
          textStyle: {
            color: '#5B5D5F',
            fontSize: 11
          }
        },
        calculable: true,
        series: [{
          name: '重点案件',
          type: 'pie',
          clockwise: false,
          itemStyle: {
            shadowColor: 'rgba(0,0,0,0.24)',
            shadowBlur: 15
          },
          roseType: 'radius',
          radius: [55, 105],
          center: ['30%', '50%'],
          label: {
            formatter: '{d}%',
            fontSize: 11,
            position: 'inside'
          },
          data: [],
          animationEasing: 'cubicInOut',
          animationDuration: 2600
        }],
        color: ['#8C5CFF', '#D54EE5', '#EC6170', '#43C591', '#9ED071', '#556DD4', '#3CB8FF', '#FBD769', '#F3B041', '#812DC9', '#230041']
      },
      lengendArr: ['未触达案件数', '案件触达1次数量', '案件触达2次数量', '案件触达3次数量', '案件触达4次数量', '案件触达5次数量', '案件触达5+次数量'],
      UnCoverRate3: '',
      UnCoverRate7: '',
      reportId: localStorage.skyTrace && JSON.parse(localStorage.skyTrace).homeReportId || '',
      listLoading: false,
      tableData: [],
      isDownload: false,
      totalRow: '',
      currentRow: '',
      commonCaseTotalStream: '',
      importantCaseTotalStream: '',
      downloadLoading: false,
      filename: '案件覆盖率情况统计表',
      autoWidth: true,
      isWin32: false,
      roleModel: ''
    }
  },
  computed: {
  },
  mounted() {
    console.log(arguments)
    this.getReportViewSataCase()
    this.isWin32 = window.navigator.platform.toLowerCase() === 'win32'
    this.roleModel = this.roleModel = ['操作员', '小组', '部门'][localStorage.skyTrace && JSON.parse(localStorage.skyTrace).scope || 0]
  },
  methods: {
    backReportView() {
      this.$router.push({
        path: '/statReport/reportView'
      })
    },
    getReportViewSataCase() {
      console.log('this.reportId:', this)
      reportViewStatCase({
        reportId: this.reportId
      }).then(response => {
        console.log('getReportViewSataCase:', response, arguments)
        if (!response) {
          return
        }
        this.tableData = response.map((m, i) => {
          if (!m.unitId && !m.isAggr) {
            for (const caseSum in m.commonCase) {
              m.commonCase[caseSum] = '---'
            }
            for (const majorCase in m.importantCase) {
              m.importantCase[majorCase] = '---'
            }
          }
          return m
        })
        this.currentRow = this.totalRow = response[response.length - 1]
        // this.org = `${this.totalRow.deptName || '---'}/${this.totalRow.teamName || '---'}`
        this.org = this.totalRow.aggrName || '---'
        this.genDate = this.totalRow.statisticDate || '---'
        this.UnCoverRate3 = this.totalRow.unCoverRate3 === 0 ? 0 : this.totalRow.unCoverRate3 || '---'
        this.UnCoverRate7 = this.totalRow.unCoverRate7 === 0 ? 0 : this.totalRow.unCoverRate7 || '---'
        this.setCurrentPieChart(this.totalRow)
      }).catch(err => {
        this.$message({
          message: err && err.resultMsg || '获取案件覆盖率统计数据失败！',
          type: 'error'
        })
      })
    },
    setCurrentPieChart(currentRow) {
      // this.sumCaseData.legend.length =  this.majorCaseData.legend.length = this.
      console.log('currentRow:', currentRow)
      if (currentRow.assignCount === 0) {
        console.log(this.sumCaseData.title)
        this.isNoData = true
        this.sumCaseData.series[0].data = this.majorCaseData.series[0].data = []
        this.sumCaseData.title.text = this.majorCaseData.title.text = ''
        return
      }
      this.isNoData = false
      this.sumCaseData.title.text = this.sumCaseTitle
      this.majorCaseData.title.text = this.majorCaseTitle
      // 案件总计:sumCase
      this.reportId = currentRow.reportBaseId
      this.sumCaseData.legend.data = this.lengendArr.map((m, i) => {
        return {
          name: m,
          icon: 'circle',
          textStyle: {
            fontSize: 11
          }
        }
      })
      const commonCaseValues = Object.values(currentRow.commonCase).map(m => m === '---' ? 0 : m)
      const importantCaseValues = Object.values(currentRow.importantCase).map(m => m === '---' ? 0 : m)

      this.isSum0 = !commonCaseValues.filter(m => m).length
      this.isMajor0 = !importantCaseValues.filter(m => m).length
      this.sumCaseData.title.text = this.isSum0 ? '' : this.sumCaseTitle
      this.majorCaseData.title.text = this.isMajor0 ? '' : this.majorCaseTitle

      this.sumCaseData.series[0].data = commonCaseValues.map((m, i) => {
        if (m === 0) {
          // this.sumCaseData.legend.data[i] = { show: false }
          return
        }
        return {
          value: m,
          name: this.sumCaseData.legend.data[i].name
        }
      })
      // 重点案件:majorCase
      this.majorCaseData.legend.data = this.lengendArr.map((m, i) => {
        return {
          name: m,
          icon: 'circle',
          textStyle: {
            fontSize: 11
          }
        }
      })
      // this.majorCaseData.legend.data.shift()
      // this.majorCaseData.series[0].data.shift()
      this.majorCaseData.series[0].data = importantCaseValues.map((m, i) => {
        if (m === 0) {
          // this.sumCaseData.legend.data[i] = { show: false }
          return
        }
        return {
          value: m,
          name: this.majorCaseData.legend.data[i].name
        }
      })
    },
    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row)
    },
    downloadExcel(arg) {
      this.isDownload = true
      console.log('downloadExcel-arg:', arg, this.totalRow)
      this.handleCurrentChange(this.totalRow)
      // this.chartSnapShot()
      // this.setCurrent(this.totalRow)
    },
    chartSnapShot() {
      console.log('// chartSnapShot .... :')
      // console.log(reportCoverExport)
      reportCoverExport({
        reportId: this.reportId || JSON.parse(localStorage.skyTrace).homeReportId,
        commonCase: this.commonCaseTotalStream,
        importantCase: this.importantCaseTotalStream
      }).then(response => {
        console.log('then --- reportCoverExport:', response)
        // 处理文件流的情况
        if (!response.resultCode) {
          this.getExcelStream(response)
          return
        }
        location.href = `${route_origins}${response.uri.slice(1, response.uri.length)}`
      }).catch(err => {
        this.$message({
          message: err && err.resultMsg || '下载案件覆盖率统计数据失败！',
          type: 'error'
        })
      })
      // this.JsonToExcel()
      // open(`/report/cover/export?reportId=${this.reportId}`)
      this.handleCurrentChange(this.currentRow)
    },
    getExcelStream(raw) {
      getExcelHeaderArray(raw, data => {
        console.log('raw-data:', data)
        const _file = new FileReader(data)
        const _blob = new Blob([_file])
        _blob.createObjectURL(this.filename + parseTime(Date.now(), '{y}{m}{d}{h}{i}') + '.xlsx')
      })
    },
    JsonToExcel() {
      console.log('export_json_to_excel:')
      this.downloadLoading = true
      Export2Excel.then(excel => {
        this.roleModel = ['操作员', '小组', '部门'][localStorage.skyTrace && JSON.parse(localStorage.skyTrace).scope || 0]
        const tHeader = [this.roleModel, '组织', '分配案件数量', '案件触达率占比', '未触达率件数', '案件触达1次数量']
        const filterVal = ['unitName', 'orgName', 'assignCount', 'coverRate', 'count0', 'count1']
        const list = this.tableData.map((m, i) => {
          return {
            unitName: m.unitName || '---',
            // orgName: `${m.deptName || '---'}/${m.teamName || '---'}`,
            orgName: m.aggrName || '---',
            assignCount: m.assignCount || '---',
            coverRate: `${m.coverRate || '---'}%`,
            count0: m.commonCase.count0 || '---',
            count1: m.commonCase.count1 || '---'
          }
        })
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename + parseTime(Date.now(), '{y}{m}{d}{h}{i}'),
          autoWidth: this.autoWidth
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleCurrentChange(curRow) {
      console.log('handleCurrentChange:', curRow)
      // this.$refs.singleTable.testMethods()
      // this.org = `${curRow.deptName || '---'}/${curRow.teamName || '---'}`
      this.org = curRow.aggrName || '---'
      this.genDate = curRow.statisticDate || '---'
      this.UnCoverRate3 = curRow.unCoverRate3 === 0 ? 0 : curRow.unCoverRate3 || '---'
      this.UnCoverRate7 = curRow.unCoverRate7 === 0 ? 0 : curRow.unCoverRate7 || '---'
      if (!this.isDownload) {
        this.currentRow = curRow
      } else {
        const _canvas = document.querySelectorAll('canvas')
        this.commonCaseTotalStream = _canvas[0]
        this.importantCaseTotalStream = _canvas[1]
        setTimeout(img => {
          this.commonCaseTotalStream = this.isSum0 ? base64Str.default.chartNoData : this.commonCaseTotalStream.toDataURL()
          this.importantCaseTotalStream = this.isMajor0 ? base64Str.default.chartNoData : this.importantCaseTotalStream.toDataURL()
          this.chartSnapShot()
        }, 1000)
      }
      this.isDownload = false
      this.setCurrentPieChart(curRow)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.stat-case{
	.sidebar-t{
		background: #01011B;
		color: white;
		font-size: 16px;
		font-weight: bolder;
		text-align: center;
		padding: 21px 0;
	}
	.r-cont{
		.m-title{
			color: #4c4c4c;
			font-size: 20px;
			font-weight: bolder;
			text-align: center;
			margin-bottom: 18px;
			.back-report-view{
				background: black;
			    color: white;
			    font-size: 14px;
			    font-weight: bold;
			    padding: 3px 2px 2px 2px;
			    float: left;
			    cursor: pointer;
			}
		}
		padding: 0 10px;
		.r-top{
			.l{
				font-size: 18px;
				color: #5B5D5F;
			}
			.r{
				float: right;
				font-size: 14px;
				color: #5B5D5F;
				em{
					font-style: normal;
					margin-left: 16px;
				}
			}
		}
		.title{
			font-size: 18px;
			color: #5B5D5F;
			.download{
				float: right;
				border:none;
				background: #D8D8D8;
				border-radius: 4px;
				font-family: 'MicrosoftYaHeiUI';
				font-size: 14px;
				color: #5B5D5F;
				letter-spacing: 0.75px;
				// margin: -16px 0 16px 0;
				margin: -15px 0 12px 0;
			    padding-left: 10px;
			    padding-right: 11px;
			}
		}
		.chart{
			@keyframes nodata_anmi {
			    0%   { opacity: 0; }
			    // 80%   { opacity: 0; }
			    100%   { opacity: .5; }
			}
			margin: 12px 0 8px 0;
			&.nodata{
				.area{
					position: relative;
					&:after{
						content: '';
						position: absolute;
						left: -10px;
						right: 0;
						top: 0;
						bottom: 0;
						background-image: url(../../assets/stat_report/report_nodata.gif);
				        background-size: 200px 200px;
				        background-repeat: no-repeat;
				        background-position: center center;
						opacity: .5;
						transition: ease .5s opacity;
	                    animation: nodata_anmi .5s linear 1;
					}
				}
			}
			.el-col{
				.area{
					position: relative;
					&.sum, &.major{
						&:after{
							content: '';
							position: absolute;
							left: -10px;
							right: 0;
							top: 0;
							bottom: 0;
							background-image: url(../../assets/stat_report/report_nodata.gif);
					        background-size: 200px 200px;
					        background-repeat: no-repeat;
					        background-position: center center;
							opacity: .5;
							transition: ease .5s opacity;
		                    animation: nodata_anmi .5s linear 1;
						}
					}
					// margin: 0 0px 0 0;
					padding: 25px 0 0 0;
					background: white;
					height: 349px;
					i {
						content: '';
						width: 10px;
					    height: 19px;
					    background: white;
					    position: absolute;
					    top: 25px;
					    z-index: 99;
					}
				}
				&:last-child{
					.area { margin:0 0 0 10px; }
				}
			}
		}
		.unreach-percent{
			margin: 12px 0 28px 0;
			.el-col{
				.per{
					background: white;
					padding: 9px 0;
					position: relative;
					font-size: 14px;
					color: #232323;
					border-radius: 4px;
					padding-left: 30px;
					// margin: 0 10px 0 0;
					&:after{
						content: '';
						position: absolute;
						top:0;
						right: 0;
						border: 10px solid #0096E0;
						border-left: 10px solid transparent;
					    border-bottom: 10px solid transparent;
					    border-top-right-radius: 4px;
					}
				}
				&:last-child{
					.per { margin:0 0 0 10px; }
				}
			}
		}
		.table-detail{
			margin: 12px 0 0px 0;
			th{
				// white-space: nowrap;
			}
		}
	}
}
.fix-padding-bottom{ padding-bottom: 10px !important; }
</style>
